package org.dolphin.web.security;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.core.AuthenticationException;

public class LoginUrlAuthenticationEntryPoint extends
    org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint {
  public LoginUrlAuthenticationEntryPoint(String loginFormUrl) {
    super(loginFormUrl);
  }

  @Override
  public void commence(HttpServletRequest request, HttpServletResponse response,
      AuthenticationException authException) throws IOException, ServletException {
    if ("XMLHttpRequest".equals(request.getHeader("X-Requested-With"))) {
      response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
      String path = request.getContextPath();
      String loginFormUrl = getLoginFormUrl();
      String loginPage = path + loginFormUrl;
      PrintWriter writer = response.getWriter();
      writer.write(loginPage);
      writer.flush();
    } else {
      super.commence(request, response, authException);
    }
  }
}
